package com.example.helloworld.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;


public class HttpHelper {
	
	private static final String TAG_STRING = "HTTP-";
	
	public static void test(){
		String httpUrl = "http://180.76.135.96/androidController/getRankDetail.action";
		doPost(httpUrl, null);
	}
	public static String doPost(String url, Map<String,String> params){
		BufferedReader in = null;
		String resultStr = null;
        try {  
            HttpClient client = new DefaultHttpClient();  
            HttpPost request = new HttpPost(url);  
            //使用NameValuePair来保存要传递的Post参数  
            List<NameValuePair> postParameters = new ArrayList<NameValuePair>();  
            //添加要传递的参数    
            if(params!=null){
            	String[] keys = (String[]) params.keySet().toArray();
            	for(String key : keys){
            		postParameters.add(new BasicNameValuePair(key, params.get(key)));  
            	}
            }
            //实例化UrlEncodedFormEntity对象  
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(  
                    postParameters);  
 
            //使用HttpPost对象来设置UrlEncodedFormEntity的Entity  
            request.setEntity(formEntity);  
            HttpResponse response = client.execute(request);  
            in = new BufferedReader(  
                    new InputStreamReader(  
                            response.getEntity().getContent()));  
 
            StringBuffer string = new StringBuffer("");  
            String lineStr = "";  
            while ((lineStr = in.readLine()) != null) {  
                string.append(lineStr + "\n");  
            }  
            in.close();  
 
            resultStr = string.toString();  
        } catch(Exception e) {  
            // Do something about exceptions  
        } finally {  
            if (in != null) {  
                try {  
                    in.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
        }  
		return resultStr;
	}
}
